package com.zg.job.batch;

import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.stereotype.Component;

/**
 * <p>Description: </p>
 *
 * @author zhanfeng.liang
 * @since 2025/3/3 11:11
 */

@Component
public class PaymentProcessingTasklet implements Tasklet {

    @Autowired
    private RetryTemplate retryTemplate;

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) {
        retryTemplate.execute(context -> {
            // 执行业务逻辑（自动重试）
            boolean success = callExternalService();
            if (!success) {
                throw new RuntimeException("业务操作失败");
            }
            return RepeatStatus.FINISHED;
        });
        return RepeatStatus.FINISHED;
    }

    private boolean callExternalService() {
        // 模拟60%的成功率
        return Math.random() > 0.4;
    }
}
